package com.black.cat.jvm.classfile.attribute;

import com.black.cat.jvm.classfile.ClassReader;

import java.util.Arrays;

/**
 * @Author blackcat
 * @create 2021/8/11 20:40
 * @version: 1.0
 * @description:
 *
 * LocalVariableTable_attribute {
 * u2 attribute_name_index;
 * u4 attribute_length;
 * u2 local_variable_table_length;
 * { u2 start_pc;
 * u2 length;
 * u2 name_index;
 * u2 descriptor_index;
 * u2 index;
 * } local_variable_table[local_variable_table_length];
 * }
 */

public class LocalVariableTableAttribute  implements AttributeInfo {
    private LocalVariableTableEntry[] localVariableTable;

    @Override
    public void readInfo(ClassReader reader) {
        int length = reader.nextU2ToInt();
        localVariableTable = new LocalVariableTableEntry[length];
        for (int i = 0; i < length; i++) {
            localVariableTable[i] = new LocalVariableTableEntry(reader);
        }
    }

    private static class LocalVariableTableEntry {
        private final int startPc;
        private final int length;
        private final int nameIndex;
        private final int descriptorIndex;
        private final int index;

        public LocalVariableTableEntry(ClassReader reader) {
            startPc = reader.nextU2ToInt();
            length = reader.nextU2ToInt();
            nameIndex = reader.nextU2ToInt();
            descriptorIndex = reader.nextU2ToInt();
            index = reader.nextU2ToInt();
        }

        @Override
        public String toString() {
            return "LineNumberTableEntry{" +
                    ",startPc=" + startPc +
                    ", length=" + length +
                    ",nameIndex=" + nameIndex +
                    ", descriptorIndex=" + descriptorIndex +
                    ", index=" + index +
                    "}";
        }
    }

    @Override
    public String toString() {
        return "LocalVariableTableAttribute{" +
                "localVariableTable=" + Arrays.toString(localVariableTable) +
                "}";
    }
}
